package com.tingyuge.base.jdk.io.nio.select;

import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.time.LocalDateTime;
import java.util.Iterator;
import java.util.Scanner;

/**
 * @author xiaodao
 * @version 1.0
 * @description
 */
public class SelectorDemo1 {

    @Test
    public void serverDemo() throws IOException {
        //1.获取服务通道
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        //2.切换非阻塞模式
        serverSocketChannel.configureBlocking(false);
        //3.创建buffer
        ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
        //4.绑定端口
        serverSocketChannel.bind(new InetSocketAddress(8080));
        //5.获取selector选择器
        Selector selector = Selector.open();
        //6.通道注册选择器,进行监听
        SelectionKey selectionKey = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        //7.选择器进行轮询,进行后续的操作
        while (selector.select() > 0) {
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {

                //获取到就绪的操作
                SelectionKey key = iterator.next();
                //判断什么操作
                if (key.isAcceptable()) {
                    //获取连接
                    SocketChannel accept = serverSocketChannel.accept();
                    //切换非阻塞模式
                    accept.configureBlocking(false);
                    //注册
                    accept.register(selector, SelectionKey.OP_READ);
                } else if (key.isConnectable()) {

                    // a connection was established with a remote server.

                } else if (key.isReadable()) {
                    SocketChannel channel = (SocketChannel) key.channel();
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    int read = channel.read(byteBuffer);
                    if (read > 0) {
                        byteBuffer.flip();
                        System.out.println(new String(byteBuffer.array(), 0, read));
                        byteBuffer.clear();
                    } else {
                        //链路已经关闭，释放资源
                        key.cancel();
                        channel.close();
                    }
                } else if (key.isWritable()) {

                    // a channel is ready for writing

                }
                iterator.remove();
            }
        }


    }

    @Test
    public void clientDemo() throws IOException {
        //1.获取通道,绑定主机和端口
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8080));
        //2.切换到非阻塞
        socketChannel.configureBlocking(false);
        //3.创建buffer
        ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
        //4.写入buffer
        buffer.put(("i'm client " + LocalDateTime.now()).getBytes());
        //5.模式切换
        buffer.flip();
        //6.写入 通道
        socketChannel.write(buffer);
        //7.清空关闭
        buffer.clear();
    }

    public static void main(String[] args) throws IOException {

        //1.获取通道,绑定主机和端口
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8080));
        //2.切换到非阻塞
        socketChannel.configureBlocking(false);
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()){
            String str = scanner.next();
            //3.创建buffer
            ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
            //4.写入buffer
            buffer.put(("i'm client " + LocalDateTime.now()+"--"+str).getBytes());
            //5.模式切换
            buffer.flip();
            //6.写入 通道
            socketChannel.write(buffer);
            //7.清空关闭
            buffer.clear();
        }


    }
}
